<template>
  <view class="members" :class="{ readonly: !enableEdit }">
    <view class="title">
      <view class="title-name">成员列表</view>
      <view v-if="checkedMemberId" class="operate-box">
        <view class="operate-btn" @click="changeProjectOwner()">
          设为负责人
        </view>
        <view class="operate-btn" @click="deleteMembers()">
          删除
        </view>
      </view>
    </view>
    <view class="member-list">
      <view
        v-for="item in members"
        :key="item.id" class="member-item"
        :class="{ active: checkedMemberId === item.id }"
        @click="onChooseItem(item)">
        <view v-if="!item.isOwner && !item.isPendingApprove" class="item-operate-box">
          <view class="like-radio" :class="{ active: checkedMemberId === item.id }"></view>
        </view>
        <view class="item-content">
          <view class="member-info">
            <i v-if="!item.userIcon" class="user-icon iconfont icon-userCenter" />
            <image v-else class="user-icon" :src="item.userIcon" mode="aspectFill"></image>
            <view class="user-name">{{ item.userName }}</view>
            <view v-if="item.isOwner" class="owner-symbol">
              负责人
            </view>
            <view class="user-phone">{{ item.phoneShow }}</view>
          </view>
          <view v-if="item.isPendingApprove" class="item-operate">
            <text class="status-text">{{item.stateText}}</text>
            <template v-if="item.canApprove">
              <text class="state-action" @click="auditMember(item, 1)">通过</text>
              <text class="state-action" @click="auditMember(item, 2)">拒绝</text>
            </template>
            <template v-if="item.canDelete">
              <text class="state-action" @click="doDeleteMember(item.id)">删除</text>
            </template>
          </view>
        </view>
      </view>
    </view>
    <uni-popup ref="deleteDialog" type="dialog">
      <uni-popup-dialog type="error" cancelText="否" confirmText="是" content="确定要删除？" @confirm="doDeleteMember(checkedMemberId)"></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="changeOwnerDialog" type="dialog">
      <uni-popup-dialog type="info" cancelText="否" confirmText="是" :content="`确定要将 ${targetOwnerName} 设置为管理员？`" @confirm="setProjectOwner()"></uni-popup-dialog>
    </uni-popup>
    <view class="invite-member" @click="shareProject()">邀请成员</view>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { getImagePath, formatPhone } from '@/utils/index.js'
export default {
  mixins: [mixin],
  props: {
    projectInfo: {
      type: Object
    }
  },
  data() {
    return {
      members: [],
      memberMap: {},
      checkedMemberId: '',
      targetOwnerName: ''
    }
  },
  computed: {
    enableEdit() {
      return this.projectInfo.canEdit
    },
    memberIds() {
      return Array.from(this.members.filter(item => !item.isOwner), item => item.id)
    }
  },
  watch: {
    projectInfo() {
      this.initData()
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      const self = this
      self.checkedMemberId = ''
      if (self.projectInfo && Array.isArray(self.projectInfo.members)) {
        const arr = []
        self.projectInfo.members.forEach(item => {
          const member = {
            id: item.user_id,
            isOwner: item.user_id === self.projectInfo.user_id,
            userIcon: getImagePath(item.photo),
            userName: item.user_name || '未设置昵称',
            userRole: item.user_role,
            phoneShow: self.enableEdit ? item.phone : formatPhone(item.phone),
            permission: item.permission,
            checkedPermission: [],
            isPendingApprove: false,
            canApprove: false,
            canDelete: false,
          }
          if (item.state === 0) {
            member.isPendingApprove = true;
            member.canApprove = self.enableEdit;
            member.stateText = '待审核';
          }
          if (item.state === 2) {
            member.isPendingApprove = true;
            member.canDelete = self.enableEdit;
            member.stateText = '已拒绝';
          }
          self.memberMap[member.id] = member
          if (member.isOwner) {
            arr.unshift(member)
          } else {
            arr.push(member)
          }
        })
        self.members = arr
      }
    },
    auditMember(target, state) {
      const self = this
      uni.request({
        url: '/project_members/modify',
        data: {
          xm_id: self.projectInfo.id,
          state,
          user_id: target.id,
        },
        success(result) {
          if (result.data.success) {
            if (state === 2) {
              target.stateText = '已拒绝';
            }
            uni.showToast({
              title: '审核成功',
              icon: 'none',
              duration: 2000
            })
            self.$emit('refresh')
          }
        }
      })
    },
    onChooseItem(item) {
      const self = this
      if (!self.enableEdit) return;
      if (item.isOwner || item.isPendingApprove) return
      self.checkedMemberId = item.id
    },
    deleteMembers() {
      this.$refs.deleteDialog.open()
    },
    doDeleteMember(userId) {
      const self = this
      uni.request({
        url: '/project_members/del',
        method: 'POST',
        data: {
          user_id: userId,
          xm_id: self.projectInfo.id
        },
        success(result) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          })
          self.$emit('refresh')
        }
      })
    },
    changeProjectOwner() {
      const self = this
      const targetOwnerId = self.checkedMemberId
      const targetOwner = self.members.find((item) => item.id === targetOwnerId)
      if (targetOwner) {
        self.targetOwnerName = targetOwner.userName
        self.$refs.changeOwnerDialog.open()
      }
    },
    setProjectOwner() {
      const self = this
      const targetOwnerId = self.checkedMemberId
      if (!targetOwnerId) return
      uni.request({
        url: '/project/modify',
        method: 'POST',
        data: {
          id: self.projectInfo.id,
          user_id: targetOwnerId
        },
        success(result) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          })
          self.$emit('refresh')
        }
      })
    },
    toAddMember() {
      uni.navigateTo({
        url: `/pages/project-detail/add-member/add-member?ids=${this.memberIds.join(',')}&projectId=${this.projectInfo.id}`
      })
    },
    shareProject() {
      this.$emit('openShare')
    }
  }
}
</script>

<style lang="scss" scoped>
.members {
  border-radius: 10rpx;
  background-color: $white;
  padding: 20rpx 30rpx 30rpx;
  &.readonly {
    .operate-box {
      display: none;
    }
    .member-item {
      padding-left: 0;
      .item-operate-box {
        display: none;
      }
    }
    .page-bottom-btn {
      display: none;
    }
    .invite-member {
      display: none;
    }
  }
}
.title {
  position: relative;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 20rpx;
  &:before {
    position: absolute;
    left: 0;
    display: block;
    content: ' ';
    width: 6rpx;
    height: 30rpx;
    background-color: $primary;
    border-radius: 4rpx;
  }
  .title-name {
    font-size: $font-size-5;
    font-weight: bold;
  }
  .operate-box {
    display: flex;
    .operate-btn {
      display: flex;
      align-items: center;
      height: 48rpx;
      border: 2rpx solid $border-base;
      border-radius: 24rpx;
      padding: 0 20rpx;
      color: $text-base;
      font-size: $font-size-1;
      margin-left: 20rpx;
    }
  }
}
.member-list {
  margin-top: 20rpx;
}
.member-item {
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 52rpx;
  &:first-child {
    margin-top: 0;
  }
  &.active {
    .item-content {
      border-color: $primary;
    }
  }
  .item-operate-box {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
  }
  .item-content {
    flex: 1;
    border: 2rpx solid $border-base;
    border-radius: 10rpx;
    padding: 20rpx;
  }
}
.member-info {
  position: relative;
  padding-left: 68rpx;
  padding-right: 170rpx;
  display: flex;
  align-items: center;
  .user-icon {
    position: absolute;
    left: 0;
    width: 48rpx;
    height: 48rpx;
    border-radius: 50%;
    font-size: 48rpx;
    color: $primary;
  }
  .user-name {
    font-size: $font-size-3;
    max-width: 200rpx;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .owner-symbol {
    margin-left: 10rpx;
    font-size: $font-size-0;
    color: $white;
    padding: 4rpx 6rpx;
    border-radius: 6rpx;
    background-color: $primary;
  }
  .role {
    margin-left: 10rpx;
    font-size: $font-size-0;
    color: $text-secondary;
  }
  .user-phone {
    position: absolute;
    right: 0;
    font-size: $font-size-3;
    color: $text-base;
  }
}
.item-operate {
  margin-top: 20rpx;
  padding-left: 68rpx;
  font-size: $font-size-3;
  .status-text {
    color: $text-base;
    margin-right: 40rpx;
  }
  .state-action {
    padding: 8rpx 16rpx;
    color: $primary;
    margin-left: 80rpx;
  }
}
.invite-member {
  position: fixed;
  right: 20rpx;
  bottom: 150rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  padding: 20rpx;
  background-color: $primary;
  color: $white;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: $font-size-1;
  box-shadow: 0 0 12rpx -2rpx $primary;
}
</style>
